<template>
  <div id="category-manager-containier">
    <el-card style="width: 500px">
      <template #header v-if="hasPerm('category_p_cd')">
        <div class="card-content">
          <el-text type="primary" style="width: 100%; text-align: center" size="large">创建大类别</el-text>
          <el-input
            v-model="createParentCategoryName"
            placeholder="请输入新大类别名称"
            :suffix-icon="EditPen"
            style="width: 300px; margin-right: 10px"
          />
          <el-button type="primary" @click="createParentCategoryHandle">创建</el-button>
        </div>
      </template>
      <div class="card-content" v-if="hasPerm('category_c_cd')">
        <el-text type="primary" style="width: 100%; text-align: center" size="large">创建数据集</el-text>
        <el-input v-model="createSubCategoryName" placeholder="请输入新数据集名称" style="width: 400px">
          <template #prepend>
            <el-select v-model="selectPCategoryId" placeholder="选择大类别" style="width: 118px">
              <el-option
                v-for="category in allPCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="EditPen" @click="createDataSetHandle" />
          </template>
        </el-input>
      </div>
      <template #footer v-if="hasPerm('category_c_cd')">
        <div class="card-content">
          <el-text type="primary" style="width: 100%; text-align: center" size="large">删除数据集</el-text>
          <el-cascader
            :key="allPCategories"
            :props="selectorProps"
            v-model="removeDataSet"
            clearable
            placeholder="请选择数据集"
            style="margin-right: 10px"
          />
          <el-button type="primary" @click="preRemoveDataSet">删除</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  getParentCategoriesApi,
  createParentCategoryApi,
  createSubCategoryApi,
  getSubCategoriesApi,
  deleteSubCategoryApi
} from "@/api/data-manager/categoryApi"
import { onMounted, ref } from "vue"
import { CascaderProps, ElMessage } from "element-plus"
import { EditPen } from "@element-plus/icons-vue"
import emitter from "@/utils/mitt"
import { openConfirmBox } from "@/utils/confirmBox"
import { useLoginStore } from "@/store/loginStore"

const loginStore = useLoginStore()

function hasPerm(perm: string) : boolean {
    return loginStore.perms.includes(perm)
}

const removeDataSet = ref()

function preRemoveDataSet() {
  if (!removeDataSet.value) {
    ElMessage.warning("请选择数据集")
    return
  }
  openConfirmBox("确认删除吗？数据集图片也会一并删除", removeDataSetHandle)
}

function removeDataSetHandle() {
  setTimeout(async () => {
    let res
    try {
      res = await deleteSubCategoryApi(removeDataSet.value[1])
    } catch (error) {
      ElMessage.error("删除操作失败")
      return
    }
    ElMessage.success("操作成功")
    emitter.emit("DM:subcatrgory-change")
  })
}

const selectorProps: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level } = node
    setTimeout(async () => {
      if (level === 0) {
        let res
        try {
          res = await getParentCategoriesApi()
        } catch (error) {
          ElMessage.error("获取大类别列表失败")
          return
        }
        resolve(
          (res.data as any[]).map((data) => ({
            value: data.id,
            label: data.name,
            leaf: false
          }))
        )
      } else {
        let res
        try {
          res = await getSubCategoriesApi(String(<number>node.value))
        } catch (error) {
          ElMessage.error("获取数据集列表失败")
          return
        }
        resolve(
          (res.data as any[]).map((data) => ({
            value: data.id,
            label: data.name,
            leaf: true
          }))
        )
      }
    })
  }
}

const createSubCategoryName = ref<string>()
const selectPCategoryId = ref<number>()

function createDataSetHandle() {
  if (!selectPCategoryId.value) {
    ElMessage.warning("请选择大类别")
    return
  } else if (
    !(createSubCategoryName.value && createSubCategoryName.value !== "") ||
    /^\s*$/.test(createSubCategoryName.value)
  ) {
    ElMessage.warning("请输入数据集名称")
    return
  }
  setTimeout(async () => {
    let res: any
    try {
      res = await createSubCategoryApi(createSubCategoryName.value?.trim()!, selectPCategoryId.value!)
    } catch (error) {
      ElMessage.error("创建失败")
      return
    }
    if (res.status !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("操作成功")
    createSubCategoryName.value = ""
    emitter.emit("DM:subcatrgory-change")
    return
  })
}

const allPCategories = ref<any[]>([])

const createParentCategoryName = ref<string>()

function createParentCategoryHandle() {
  if (
    !(createParentCategoryName.value && createParentCategoryName.value !== "") ||
    /^\s*$/.test(createParentCategoryName.value)
  ) {
    ElMessage.warning("请输入名称")
    return
  }
  setTimeout(async () => {
    let res: any
    try {
      res = await createParentCategoryApi(createParentCategoryName.value?.trim()!)
    } catch (error) {
      ElMessage.error("创建失败")
      return
    }
    if (res.status !== 200) {
      ElMessage.error(res.msg)
      return
    }
    ElMessage.success("操作成功")
    createParentCategoryName.value = ""
    emitter.emit("DM:pcatrgory-change")
    getAllPCategories()
  })
}

onMounted(() => {
  getAllPCategories()
})

function getAllPCategories() {
  setTimeout(async () => {
    let res
    try {
      res = await getParentCategoriesApi()
    } catch (error) {
      ElMessage.error("获取大类别数据失败")
      return
    }
    allPCategories.value = res.data
  })
}
</script>

<style lang="scss" scoped>
#category-manager-containier {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .card-content {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
  }
}
</style>
